package toy.keli.edic.ui.main.components

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.SubcomposeLayout
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import toy.keli.edic.ui.main.components.Display.mt
import androidx.compose.foundation.layout.FlowRow as FlowRow0


@OptIn(ExperimentalLayoutApi::class)
@Composable
fun FlowRow(
    modifier: Modifier = Modifier,
    horizontalArrangement: Arrangement.Horizontal = Arrangement.Start,
    verticalArrangement: Arrangement.Vertical = Arrangement.Top,
    maxItemsInEachRow: Int = Int.MAX_VALUE,
    maxLines: Int = Int.MAX_VALUE,
    content: @Composable () -> Unit
){
    FlowRow0 (
        modifier,
        horizontalArrangement,
        verticalArrangement,
        maxItemsInEachRow,
        maxLines,
        content = {
            content()
        }
    )
}


/**
 * 限制最多3行的FlowRow，超过部分显示省略提示
 * @param items 所有数据项
 * @param itemContent 单个项的UI
 * @param overflowHint 超过3行时的提示（默认显示"+X项"）
 */
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun <T> LimitedFlowRow(
    items: List<T>,
    maxLines: Int=3,
    modifier: Modifier = Modifier,
    singleLineHeight: Dp = 40.dp, // 允许外部指定单行高度（更灵活）
    overflowHint: @Composable (Int,onClick:()->Unit) -> Unit = { remaining,onClick ->
        Text(
            text = "+$remaining "+mt("项"),
            modifier = Modifier.padding(horizontal = 4.dp).clickable {
                onClick();
            },
            color = androidx.compose.ui.graphics.Color.Gray,
        )
    },
    itemContent: @Composable (T) -> Unit,
) {
    var visibleCount = items.size
    var hasOverflow by remember { mutableStateOf(false) }
    var showOverflow by remember { mutableStateOf(false) }
    if(!showOverflow) {
        // 1. 自定义布局：仅负责测量和布局，不处理状态更新
        SubcomposeLayout(modifier = modifier) { constraints ->
            // 2. 测量当前可见项（不包含省略提示）
            val itemsMeasurable = subcompose("items") {
                FlowRow0 {
                    items.take(visibleCount).forEach { itemContent(it) }
                }
            }
            val itemsPlaceable = itemsMeasurable.first().measure(constraints)

            // 3. 计算最大允许高度（单行高度 × 最大行数）
            val maxAllowedHeight = with(this) { singleLineHeight.toPx() }.toInt() * maxLines

            // 4. 直接同步判断是否超过行数（关键：不使用LaunchedEffect）
            val isOverMaxLines = itemsPlaceable.height > maxAllowedHeight

            // 5. 同步更新状态（在布局测量完成后）
            if (isOverMaxLines && visibleCount > 0) {
                val size:Double = maxAllowedHeight.toDouble()/itemsPlaceable.height*0.5;
                visibleCount = (visibleCount*size).toInt().coerceAtLeast(0)
            }
            if (visibleCount < items.size) {
                hasOverflow = true
            } else {
                hasOverflow = false
            }

            // 6. 测量包含省略提示的最终布局
            val finalMeasurable = subcompose("final") {
                FlowRow0(maxLines = maxLines) {
                    items.take(visibleCount).forEach { itemContent(it) }
                    if (hasOverflow) {
                        overflowHint(items.size - visibleCount){
                            showOverflow=true;
                        }
                    }
                }
            }
            val finalPlaceable = finalMeasurable.first().measure(constraints)

            // 7. 放置最终布局
            layout(finalPlaceable.width, finalPlaceable.height) {
                finalPlaceable.place(0, 0)
            }
        }
    }else{
        FlowRow0 {
            items.forEach { itemContent(it) }
        }
    }
}